import random
import cranesched
from cranesched.solvers import DFS


def random_coords_generator(width=10.0, height=10.0):
    def generate_coords(places):
        coords = {}
        for place in places:
            if "coords" not in place.meta:
                x = float(random.randrange(0, width))
                y = float(random.randrange(0, height))
                place.meta.coords = (x, y)
            coords[place.gid] = place.meta.coords
        return coords
    return generate_coords
    
    
    
### create a CS instance from an SP solution
##from stacking.example import *
##cs = cranesched.Instance.from_sp_solution(s.solution, 10, 20, 
##                                          coords_fnc=random_coords_generator(), seed=0)
##cs.preprocess()
##cs.save("test0.csi")

#cs = cranesched.Instance.load("test0.csi")

#dfs = DFS()
#dfs.driver.init(cs)  # --> initialize solver
#dfs.driver.run()     # --> bootstrap and run search

sp = stacking.Instance.load("foo.sp_i")
sp_sol = HeuristicSolver(heuristics.FO).solve(sp, seed=0)
sp_sol.save("foo.sp_s")

dfs = DFS()  # depth-first search BB solver for crane scheduling
for i, j, cs in cranesched.Instance.slices_sp_solution(sp_sol):
    filename = "foo_%d_%d" % (i, j)
    cs.save(filename + ".cs_i")
    dfs.driver.init(cs)
    cs_sol = dfs.driver.run()
    cs_sol.save(filename + ".cs_s")
    
    
